<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>俄罗斯方块游戏</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        
        .game-container {
            background: white;
            border-radius: 15px;
            padding: 5px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.3);
            max-width: 100%;
            width: 100%;
            text-align: center;
        }
        
        h1 {
            color: #333;
            margin-bottom: 20px;
            font-size: 2.5em;
        }
        
        .game-area {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 20px;
        }
        
        #gameCanvas {
            border: 3px solid #333;
            border-radius: 8px;
            background: #f0f0f0;
            max-width: 100%;
            height: auto;
        }
        
        .game-info {
            flex: 1;
            text-align: left;
        }
        
        .score-board {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .score-board h3 {
            margin: 0 0 10px 0;
            color: #333;
        }
        
        .score-board p {
            margin: 5px 0;
            font-size: 18px;
            font-weight: bold;
        }
        
        .controls {
            background: #f8f9fa;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .controls h3 {
            margin: 0 0 10px 0;
            color: #333;
        }
        
        .controls p {
            margin: 5px 0;
            font-size: 14px;
        }
        
        .game-buttons {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        button {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .btn-primary {
            background: #007bff;
            color: white;
        }
        
        .btn-primary:hover {
            background: #0056b3;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #6c757d;
            color: white;
        }
        
        .btn-secondary:hover {
            background: #545b62;
            transform: translateY(-2px);
        }
        
        @media (max-width: 768px) {
            .game-container {
                padding: 5px;
            }
            
            .game-area {
                flex-direction: column;
                align-items: center;
            }
            
            .mobile-controls {
                order: 2;
                margin-top: 10px;
                margin-bottom: 10px;
            }
            
            .game-info {
                order: 3;
                width: 100%;
            }
            
            .score-board, .controls {
                padding: 8px;
                margin-bottom: 10px;
            }
            
            .controls p {
                font-size: 12px;
            }
            
            h1 {
                font-size: 1.8em;
                margin-bottom: 10px;
            }
        }
        
        .mobile-controls {
            display: none;
            margin-top: 15px;
            margin-bottom: 15px;
        }
        
        .control-row {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin: 10px 0;
        }
        
        .control-btn {
            width: 60px;
            height: 60px;
            border-radius: 50%;
            border: 2px solid #333;
            background: #007bff;
            color: white;
            font-size: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            user-select: none;
            transition: all 0.2s ease;
            -webkit-tap-highlight-color: transparent;
            touch-action: manipulation;
        }
        
        .control-btn:hover {
            background: #0056b3;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .control-btn:active, .control-btn.pressed {
            background: #004494;
            transform: scale(0.95);
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        
        @media (max-width: 768px) {
            .mobile-controls {
                display: block;
                margin-top: 5px;
                margin-bottom: 5px;
            }
            
            .control-row {
                margin: 5px 0;
            }
            
            .control-btn {
                width: 50px;
                height: 50px;
                font-size: 20px;
            }
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>🎮 俄罗斯方块游戏</h1>
        
        <div class="game-area">
            <canvas id="gameCanvas" width="300" height="600"></canvas>
            
            <div class="mobile-controls">
                <div class="control-row">
                    <div class="control-btn" ontouchstart="handleTouch(event, 'left');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'left');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">←</div>
                    <div class="control-btn" ontouchstart="handleTouch(event, 'down');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'down');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">↓</div>
                    <div class="control-btn" ontouchstart="handleTouch(event, 'right');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'right');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">→</div>
                </div>
                <div class="control-row">
                    <div class="control-btn" ontouchstart="handleTouch(event, 'rotate');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'rotate');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">↻</div>
                    <div class="control-btn" ontouchstart="handleTouch(event, 'drop');" ontouchend="handleTouchEnd(event);" onmousedown="handleMouseDown(event, 'drop');" onmouseup="handleMouseUp(event);" onmouseleave="handleMouseUp(event);">⬇</div>
                </div>
            </div>
            
            <div class="game-info">
                <div class="game-buttons">
            <button class="btn-primary" onclick="startGame()">开始游戏</button>
            <button class="btn-secondary" onclick="pauseGame()">暂停游戏</button>
            <button class="btn-secondary" onclick="resetGame()">重新开始</button>
        </div>
        
                <div class="score-board">
                    <h3>📊 游戏统计</h3>
                    <p>分数: <span id="score">0</span></p>
                    <p>等级: <span id="level">1</span></p>
                    <p>消除行数: <span id="lines">0</span></p>
                </div>
                
                <div class="controls">
                    <h3>🎯 操作说明</h3>
                    <p>← → : 左右移动</p>
                    <p>↓ : 加速下落</p>
                    <p>↑ : 旋转方块</p>
                    <p>空格 : 直接落下</p>
                </div>
            </div>
        </div>
    <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        
        // 游戏常量
        const BOARD_WIDTH = 10;
        const BOARD_HEIGHT = 20;
        
        // 根据屏幕大小调整方块大小
        function getBlockSize() {
            if (window.innerWidth <= 768) {
                return Math.min(25, (window.innerWidth - 60) / BOARD_WIDTH);
            }
            return 30;
        }
        
        let BLOCK_SIZE = getBlockSize();
        
        // 调整画布大小
        function resizeCanvas() {
            BLOCK_SIZE = getBlockSize();
            canvas.width = BOARD_WIDTH * BLOCK_SIZE;
            canvas.height = BOARD_HEIGHT * BLOCK_SIZE;
            drawBoard();
        }
        
        // 监听窗口大小变化
        window.addEventListener('resize', resizeCanvas);
        
        // 游戏状态
        let gameBoard = [];
        
        // 初始化游戏板
        function initGame() {
            initBoard();
            resizeCanvas();
            drawBoard();
        }
        
        // 页面加载完成后初始化游戏
        window.addEventListener('load', initGame);
        let currentPiece = null;
        let gameRunning = false;
        let gamePaused = false;
        let score = 0;
        let level = 1;
        let lines = 0;
        let dropTime = 0;
        let dropInterval = 1000;
        
        // 方块形状定义
        const PIECES = [
            // I形
            {
                shape: [
                    [1, 1, 1, 1]
                ],
                color: '#00f0f0'
            },
            // O形
            {
                shape: [
                    [1, 1],
                    [1, 1]
                ],
                color: '#f0f000'
            },
            // T形
            {
                shape: [
                    [0, 1, 0],
                    [1, 1, 1]
                ],
                color: '#a000f0'
            },
            // S形
            {
                shape: [
                    [0, 1, 1],
                    [1, 1, 0]
                ],
                color: '#00f000'
            },
            // Z形
            {
                shape: [
                    [1, 1, 0],
                    [0, 1, 1]
                ],
                color: '#f00000'
            },
            // J形
            {
                shape: [
                    [1, 0, 0],
                    [1, 1, 1]
                ],
                color: '#0000f0'
            },
            // L形
            {
                shape: [
                    [0, 0, 1],
                    [1, 1, 1]
                ],
                color: '#f0a000'
            }
        ];
        
        // 初始化游戏板
        function initBoard() {
            gameBoard = [];
            for (let y = 0; y < BOARD_HEIGHT; y++) {
                gameBoard[y] = [];
                for (let x = 0; x < BOARD_WIDTH; x++) {
                    gameBoard[y][x] = 0;
                }
            }
        }
        
        // 创建新方块
        function createPiece() {
            const pieceType = Math.floor(Math.random() * PIECES.length);
            return {
                shape: PIECES[pieceType].shape,
                color: PIECES[pieceType].color,
                x: Math.floor(BOARD_WIDTH / 2) - Math.floor(PIECES[pieceType].shape[0].length / 2),
                y: 0
            };
        }
        
        // 绘制方块
        function drawBlock(x, y, color) {
            ctx.fillStyle = color;
            ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
            ctx.strokeStyle = '#333';
            ctx.strokeRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE);
        }
        
        // 绘制游戏板
        function drawBoard() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 确保gameBoard已初始化
            if (!gameBoard || gameBoard.length === 0) {
                initBoard();
            }
            
            // 绘制已固定的方块
            for (let y = 0; y < BOARD_HEIGHT; y++) {
                // 确保每一行都已初始化
                if (!gameBoard[y]) {
                    gameBoard[y] = new Array(BOARD_WIDTH).fill(0);
                }
                
                for (let x = 0; x < BOARD_WIDTH; x++) {
                    if (gameBoard[y][x]) {
                        drawBlock(x, y, gameBoard[y][x]);
                    }
                }
            }
            
            // 绘制当前方块
            if (currentPiece) {
                for (let y = 0; y < currentPiece.shape.length; y++) {
                    for (let x = 0; x < currentPiece.shape[y].length; x++) {
                        if (currentPiece.shape[y][x]) {
                            drawBlock(currentPiece.x + x, currentPiece.y + y, currentPiece.color);
                        }
                    }
                }
            }
        }
        
        // 检查碰撞
        function checkCollision(piece, dx = 0, dy = 0) {
            // 确保gameBoard已初始化
            if (!gameBoard || gameBoard.length === 0) {
                return false;
            }
            
            for (let y = 0; y < piece.shape.length; y++) {
                for (let x = 0; x < piece.shape[y].length; x++) {
                    if (piece.shape[y][x]) {
                        const newX = piece.x + x + dx;
                        const newY = piece.y + y + dy;
                        
                        if (newX < 0 || newX >= BOARD_WIDTH || newY >= BOARD_HEIGHT) {
                            return true;
                        }
                        
                        // 确保gameBoard[newY]已初始化
                        if (newY >= 0 && newY < gameBoard.length) {
                            if (!gameBoard[newY]) {
                                gameBoard[newY] = new Array(BOARD_WIDTH).fill(0);
                            }
                            if (gameBoard[newY][newX]) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }
        
        // 固定方块
        function lockPiece() {
            // 确保gameBoard已初始化
            if (!gameBoard || gameBoard.length === 0) {
                initBoard();
            }
            
            for (let y = 0; y < currentPiece.shape.length; y++) {
                for (let x = 0; x < currentPiece.shape[y].length; x++) {
                    if (currentPiece.shape[y][x]) {
                        const boardY = currentPiece.y + y;
                        const boardX = currentPiece.x + x;
                        if (boardY >= 0) {
                            // 确保gameBoard[boardY]已初始化
                            if (!gameBoard[boardY]) {
                                gameBoard[boardY] = new Array(BOARD_WIDTH).fill(0);
                            }
                            gameBoard[boardY][boardX] = currentPiece.color;
                        }
                    }
                }
            }
        }
        
        // 消除完整行
        function clearLines() {
            // 确保gameBoard已初始化
            if (!gameBoard || gameBoard.length === 0) {
                return;
            }
            
            let linesCleared = 0;
            
            for (let y = BOARD_HEIGHT - 1; y >= 0; y--) {
                // 确保gameBoard[y]已初始化
                if (!gameBoard[y]) {
                    gameBoard[y] = new Array(BOARD_WIDTH).fill(0);
                    continue;
                }
                
                if (gameBoard[y].every(cell => cell !== 0)) {
                    gameBoard.splice(y, 1);
                    gameBoard.unshift(new Array(BOARD_WIDTH).fill(0));
                    linesCleared++;
                    y++; // 重新检查当前行
                }
            }
            
            if (linesCleared > 0) {
                lines += linesCleared;
                score += linesCleared * 100 * level;
                level = Math.floor(lines / 10) + 1;
                dropInterval = Math.max(100, 1000 - (level - 1) * 100);
                updateScore();
            }
        }
        
        // 旋转方块
        function rotatePiece() {
            if (!currentPiece || !gameRunning || gamePaused) return;
            const rotated = [];
            const rows = currentPiece.shape.length;
            const cols = currentPiece.shape[0].length;
            
            for (let x = 0; x < cols; x++) {
                rotated[x] = [];
                for (let y = rows - 1; y >= 0; y--) {
                    rotated[x][rows - 1 - y] = currentPiece.shape[y][x];
                }
            }
            
            const originalShape = currentPiece.shape;
            currentPiece.shape = rotated;
            
            if (checkCollision(currentPiece)) {
                currentPiece.shape = originalShape;
            }
        }
        
        // 移动方块
        function movePiece(dx, dy) {
            if (!currentPiece || !gameRunning || gamePaused) return false;
            if (!checkCollision(currentPiece, dx, dy)) {
                currentPiece.x += dx;
                currentPiece.y += dy;
                return true;
            }
            return false;
        }
        
        // 直接落下
        function dropPiece() {
            if (!currentPiece || !gameRunning || gamePaused) return;
            while (movePiece(0, 1)) {
                // 继续下落
            }
        }
        
        // 更新分数显示
        function updateScore() {
            document.getElementById('score').textContent = score;
            document.getElementById('level').textContent = level;
            document.getElementById('lines').textContent = lines;
        }
        
        // 游戏主循环
        function gameLoop(timestamp) {
            if (!gameRunning || gamePaused) return;
            
            if (timestamp - dropTime > dropInterval) {
                if (!movePiece(0, 1)) {
                    lockPiece();
                    clearLines();
                    currentPiece = createPiece();
                    
                    if (checkCollision(currentPiece)) {
                        gameRunning = false;
                        alert('游戏结束！最终分数：' + score);
                        return;
                    }
                }
                dropTime = timestamp;
            }
            
            drawBoard();
            requestAnimationFrame(gameLoop);
        }
        
        // 开始游戏
        function startGame() {
            if (!gameRunning) {
                initBoard();
                currentPiece = createPiece();
                gameRunning = true;
                gamePaused = false;
                score = 0;
                level = 1;
                lines = 0;
                dropInterval = 1000;
                updateScore();
                requestAnimationFrame(gameLoop);
            }
        }
        
        // 暂停游戏
        function pauseGame() {
            gamePaused = !gamePaused;
            if (!gamePaused && gameRunning) {
                requestAnimationFrame(gameLoop);
            }
        }
        
        // 重新开始
        function resetGame() {
            gameRunning = false;
            gamePaused = false;
            initBoard();
            currentPiece = null;
            score = 0;
            level = 1;
            lines = 0;
            updateScore();
            drawBoard();
        }
        
        // 键盘控制
        document.addEventListener('keydown', (e) => {
            if (!gameRunning || gamePaused) return;
            
            switch (e.key) {
                case 'ArrowLeft':
                    movePiece(-1, 0);
                    break;
                case 'ArrowRight':
                    movePiece(1, 0);
                    break;
                case 'ArrowDown':
                    movePiece(0, 1);
                    break;
                case 'ArrowUp':
                    rotatePiece();
                    break;
                case ' ':
                    dropPiece();
                    break;
            }
            drawBoard();
        });
        
        // 触摸控制处理
        let touchInterval;
        
        function handleTouch(event, action) {
            event.preventDefault();
            
            // 如果游戏未开始，提示用户开始游戏
            if (!gameRunning) {
                showMessage('请先点击"开始游戏"按钮！');
                return;
            }
            
            // 如果游戏暂停，提示用户继续游戏
            if (gamePaused) {
                showMessage('游戏已暂停，请点击"暂停游戏"按钮继续！');
                return;
            }
            
            // 立即执行一次
            executeAction(action);
            
            // 设置连续执行（用于长按）
            touchInterval = setInterval(() => {
                executeAction(action);
            }, 150);
        }
        
        function handleTouchEnd(event) {
            event.preventDefault();
            if (touchInterval) {
                clearInterval(touchInterval);
                touchInterval = null;
            }
        }
        
        function executeAction(action) {
            switch (action) {
                case 'left':
                    movePiece(-1, 0);
                    break;
                case 'right':
                    movePiece(1, 0);
                    break;
                case 'down':
                    movePiece(0, 1);
                    break;
                case 'rotate':
                    rotatePiece();
                    break;
                case 'drop':
                    dropPiece();
                    break;
            }
            drawBoard();
        }
        
        // 鼠标控制处理（桌面端兼容）
        function handleMouseDown(event, action) {
            event.preventDefault();
            // 添加按下效果
            event.target.classList.add('pressed');
            // 复用触摸处理逻辑
            handleTouch(event, action);
        }
        
        function handleMouseUp(event) {
            event.preventDefault();
            // 移除按下效果
            if (event.target.classList.contains('pressed')) {
                event.target.classList.remove('pressed');
            }
            handleTouchEnd(event);
        }
        
        // 显示提示信息
        function showMessage(message) {
            // 创建提示元素
            const messageDiv = document.createElement('div');
            messageDiv.textContent = message;
            messageDiv.style.cssText = `
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                background: rgba(0, 0, 0, 0.8);
                color: white;
                padding: 15px 25px;
                border-radius: 10px;
                font-size: 16px;
                z-index: 1000;
                text-align: center;
            `;
            
            document.body.appendChild(messageDiv);
            
            // 2秒后自动移除提示
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 2000);
        }
        
        // 移除重复的初始化调用
    </script>
</body>
</html>